package com.huika.renrench.control.my.merchant;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.http.params.FileTypeParam;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.lib.utils.FileUtils;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.my.activity.ChoiceProvienceActivity;
import com.huika.renrench.control.my.event.ImgActionEvent;
import com.huika.renrench.control.my.event.ImgDelEvent;
import com.huika.renrench.control.my.event.ImgUpEvent;
import com.huika.renrench.control.my.merchant.xpic.Bimpx;
import com.huika.renrench.control.my.merchant.xpic.XGridAdapter;
import com.huika.renrench.control.my.merchant.xpic.XPhotoAct;
import com.huika.renrench.control.my.merchant.xpic.XPicSelectAct;
import com.huika.renrench.control.my.merchant.zpic.Bimpz;
import com.huika.renrench.control.my.merchant.zpic.ZGridAdapter;
import com.huika.renrench.control.my.merchant.zpic.ZPhotoAct;
import com.huika.renrench.control.my.merchant.zpic.ZPicSelectAct;
import com.huika.renrench.db.areainfo.AreaInfoDbHelper;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.http.ServerFlagError;
import com.huika.renrench.http.ServerJsonUnParseError;
import com.huika.renrench.support.bean.DelImgBean;
import com.huika.renrench.support.bean.LocationBean;
import com.huika.renrench.support.bean.LocationBean.MyLocationListener;
import com.huika.renrench.support.bean.MyProgramBean;
import com.huika.renrench.support.bean.MyProgramImg;
import com.huika.renrench.support.bean.UpImageBean;
import com.huika.renrench.support.bean.UpImgIdBean;
import com.huika.renrench.support.bean.UserModel;
import com.huika.renrench.utils.FileTool;
import com.huika.renrench.utils.GaodeMapHelper;
import com.huika.renrench.utils.ImageTools;
import com.huika.renrench.view.TitleBarHelper;
import com.huika.renrench.view.photos.Bimp;
import com.huika.renrench.view.photos.PhotoAct;
import com.huika.renrench.view.photos.PicSelectAct;
import com.huika.renrench.view.photos.PublicShowOrderGridAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import de.greenrobot.event.EventBus;

/**
 * @ClassName: MyProgramActivity
 * @说明: 管理我的创业项目
 * @author zwy
 * @date 2015年6月2日 下午5:49:17
 */
public class MyProgramActivity extends BaseAct implements MyLocationListener {
	private GridView displayUploadPic_gv;// 显示上传图片的视图
	private LinearLayout addPic_layout;// 点击添加图片的按钮layout
	private ImageView addPic_img;// 添加图片的按钮

	private File picFile;
	private Dialog picDialog;
	private Context mContext;
	private static final int ACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA = 3;
	public static ArrayList<String> imgUrlArray = new ArrayList<String>();
	private int count = -1;// 需要上传图片的张数
	private PublicShowOrderGridAdapter adapter;

	private Dialog zpicDialog;
	private static final int ZACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA = 4;
	private GridView showZPic;
	private LinearLayout addZPicLayout;
	private ImageView addZPic;
	private ZGridAdapter zAdapter;
	private int zCount = -1;
	public static ArrayList<String> imgZurls = new ArrayList<String>();

	private Dialog xpicDialog;
	private static final int XACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA = 5;
	private GridView showXPic;
	private LinearLayout addXPicLayout;
	private ImageView addXPic;
	private XGridAdapter xAdapter;
	private int xCount = -1;
	public static ArrayList<String> imgXurls = new ArrayList<String>();

	private EditText etMerName;
	private EditText etShopName;
	private EditText etPhone;
	private EditText tvQu;
	private EditText etAddress;
	private TextView btnRefresh;
	private EditText etProName;
	private LinearLayout layoutType;
	private EditText etTime;
	private EditText etType;
	private EditText etPrice;
	private EditText etIntroduce;
	private Button btnRelease;
	private TextView tvStatus;
	private static final int TYPE_REQUEST_CODE = 6;
	private int locationCount = 0;// 定位次数

	private UserModel userModel;
	private String typeId = "";
	private String backStr;

	private GaodeMapHelper gaodeMapHelper;
	private LocationBean locationBean;
	private boolean locationSuccess = false;
	private String mAreaID = "";
	private ImageLoader imageLoader;

	public final int REQ_CODE_SELECT_AREA = 10000;
	private ArrayList<String> tempUrls = new ArrayList<String>();
	private ArrayList<String> upUrls = new ArrayList<String>();
	private int upCount;
	private int upType;
	private boolean isUp = false;
	private ArrayList<String> tDImgUrls = new ArrayList<String>();// 上传用的临时长地址,用于删除
	private ArrayList<String> tZImgUrls = new ArrayList<String>();// 上传用的id
	private ArrayList<String> tXImgUrls = new ArrayList<String>();// 上传用的id

	private HashMap<String, String> tupImgs = new HashMap<String, String>();// 临时保存id
	private HashMap<String, String> upDImgs = new HashMap<String, String>();// 上传用的id，<短地址,imgId>
	private HashMap<String, String> upZImgs = new HashMap<String, String>();// 上传用的id
	private HashMap<String, String> upXImgs = new HashMap<String, String>();// 上传用的id

	private HashMap<String, String> delImgs = new HashMap<String, String>();// 删除<imageId,imageType>

	private int delUpCount = 0;

	private ArrayList<DelImgBean> delImgBeans = new ArrayList<DelImgBean>();
	private String userId;

	private DisplayImageOptions options;
	private String defultImg;
	private Dialog dialog;
	private boolean isUpSuccess = false;
	private ArrayList<String> tags = new ArrayList<String>();
	private ExecutorService upImgThreadPool = Executors.newFixedThreadPool(3);//上传图片的线程池

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_myprogram);
		mContext = this;
		EventBus.getDefault().register(this);
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(context));
	}

	@Override
	protected void initData() {
		userModel = GlobalApp.userModel;
		backStr = getIntent().getStringExtra("backStr");
	}

	@Override
	protected void initWidget() {
		TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1);
		titleBarHelper.setLeftMsg(backStr);
		etMerName = (EditText) findViewById(R.id.et_merchant_name_amp);
		etShopName = (EditText) findViewById(R.id.et_shope_name_amp);
		etPhone = (EditText) findViewById(R.id.et_phone_amp);
		tvQu = (EditText) findViewById(R.id.et_selectqu_amp);
		etAddress = (EditText) findViewById(R.id.et_address_amp);
		btnRefresh = (TextView) findViewById(R.id.btn_refresh_amp);
		etProName = (EditText) findViewById(R.id.et_pname_amp);
		layoutType = (LinearLayout) findViewById(R.id.layout_ptype_amp);
		etType = (EditText) findViewById(R.id.et_ptype_amp);
		etPrice = (EditText) findViewById(R.id.et_pprice_amp);
		etIntroduce = (EditText) findViewById(R.id.et_pintroduce_amp);
		etTime = (EditText) findViewById(R.id.et_ptime_amp);
		btnRelease = (Button) findViewById(R.id.btn_submit_amp);
		tvStatus = (TextView) findViewById(R.id.tv_status_amp);
		etType.setOnClickListener(this);
		tvQu.setOnClickListener(this);
		btnRelease.setOnClickListener(this);
		btnRefresh.setOnClickListener(this);
		etPhone.addTextChangedListener(phoneWatcher);

		gaodeMapHelper = new GaodeMapHelper(this);
		gaodeMapHelper.setmLocationListener(this);
		// userId = GlobalApp.userModel.getUserId();
		initUpload();
		// etPhone.setText(userModel.getPhone());
		if (userModel.getHasProject() == 0) {
			titleBarHelper.setTitleMsg("录入创业项目");
		} else {
			titleBarHelper.setTitleMsg("编辑创业项目");
			tvStatus.setVisibility(View.VISIBLE);
			initNet();
		}

		options = new DisplayImageOptions.Builder().cacheInMemory(true)// 开启内存缓存
				.showImageOnLoading(R.drawable.icon_default_big).showImageForEmptyUri(R.drawable.icon_default_big).showImageOnFail(R.drawable.icon_default_big).build();
		// initImage();
		getLocation();
	}

	private void initImage() {
		Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_default_small);
		try {
			FileTool.saveFile(rawBitmap, "default.jpg", "");
			defultImg = String.format("%s/default.jpg", FileTool.getDefaultfoldername());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initUpload() {
		displayUploadPic_gv = (GridView) findViewById(R.id.display_upload_pic);
		addPic_layout = (LinearLayout) findViewById(R.id.add_pic_layout);
		addPic_img = (ImageView) findViewById(R.id.add_pic);

		addPic_img.setOnClickListener(this);
		adapter = new PublicShowOrderGridAdapter(this);
		displayUploadPic_gv.setAdapter(adapter);
		displayUploadPic_gv.setOnItemClickListener(myClickListener);

		showZPic = (GridView) findViewById(R.id.display_upload_zpic);
		addZPicLayout = (LinearLayout) findViewById(R.id.add_zpic_layout);
		addZPic = (ImageView) findViewById(R.id.add_zpic);
		addZPic.setOnClickListener(this);
		zAdapter = new ZGridAdapter(mContext);
		showZPic.setAdapter(zAdapter);
		showZPic.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (parent.getChildCount() - 1 == position && (parent.getChildCount() != 5 || zCount == 4)) {
					addZPic();
				} else {
					Intent intent = new Intent(MyProgramActivity.this, ZPhotoAct.class);
					intent.putExtra("ID", position);
					startActivity(intent);
				}
			}
		});

		showXPic = (GridView) findViewById(R.id.display_upload_xpic);
		addXPicLayout = (LinearLayout) findViewById(R.id.add_xpic_layout);
		addXPic = (ImageView) findViewById(R.id.add_xpic);
		addXPic.setOnClickListener(this);
		xAdapter = new XGridAdapter(mContext);
		showXPic.setAdapter(xAdapter);
		showXPic.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (parent.getChildCount() - 1 == position && (parent.getChildCount() != 5 || xCount == 4)) {
					addXPic();
				} else {
					Intent intent = new Intent(MyProgramActivity.this, XPhotoAct.class);
					intent.putExtra("ID", position);
					startActivity(intent);
				}
			}
		});
	}

	@Override
	public void widgetClick(View v) {
		switch (v.getId()) {
		case R.id.add_pic:
			addPic();
			break;
		case R.id.add_zpic:
			addZPic();
			break;
		case R.id.add_xpic:
			addXPic();
			break;
		case R.id.et_selectqu_amp:
			Intent areaIntent = new Intent(this, ChoiceProvienceActivity.class);
			startActivityForResult(areaIntent, 10000);
			break;
		case R.id.et_ptype_amp:
			Intent intent = new Intent(MyProgramActivity.this, MyProgramClassifyAct.class);
			startActivityForResult(intent, TYPE_REQUEST_CODE);
			break;
		case R.id.btn_refresh_amp:// 定位
			getLocation();
			break;
		case R.id.btn_submit_amp:
			release();
			break;

		default:
			break;
		}
	}

	private void getLocation() {
		gaodeMapHelper.start();
		// showToastMsg("定位中...");
	}

	private void addPic() {
		if (picDialog == null) {
			picDialog = MMAlert.createTwoChoicAlertNoTitle(this, R.string.common_camera, R.string.common_gallery, new MMAlert.DialogOnItemClickListener() {
				@Override
				public void onItemClickListener(View v, int position) {
					upClear();
					int id = v.getId();
					switch (id) {
					case R.id.item_first:
						if (!ImageTools.isSDCardExist()) {
							ToastMsg.showToastMsg(mContext, "sd卡不可用");
							return;
						}
						Intent cameraIntent = null;
						picFile = ImageTools.initTempFile();
						cameraIntent = ImageTools.getTakeCameraIntent(Uri.fromFile(picFile));
						startActivityForResult(cameraIntent, ACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA);
						picDialog.dismiss();
						break;

					case R.id.item_second:
						Intent photoIntent = null;
						photoIntent = new Intent(mContext, PicSelectAct.class);
						mContext.startActivity(photoIntent);
						break;
					}
				}

			});
		}
		picDialog.show();
	}

	private void addZPic() {
		upClear();
		if (zpicDialog == null) {
			zpicDialog = MMAlert.createTwoChoicAlertNoTitle(this, R.string.common_camera, R.string.common_gallery, new MMAlert.DialogOnItemClickListener() {

				@Override
				public void onItemClickListener(View v, int position) {
					int id = v.getId();
					switch (id) {
					case R.id.item_first:
						if (!ImageTools.isSDCardExist()) {
							ToastMsg.showToastMsg(mContext, "sd卡不可用");
							return;
						}
						Intent cameraIntent = null;
						picFile = ImageTools.initTempFile();
						cameraIntent = ImageTools.getTakeCameraIntent(Uri.fromFile(picFile));
						startActivityForResult(cameraIntent, ZACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA);
						zpicDialog.dismiss();
						break;

					case R.id.item_second:
						Intent photoIntent = null;
						photoIntent = new Intent(mContext, ZPicSelectAct.class);
						mContext.startActivity(photoIntent);
						break;
					}
				}

			});
		}
		zpicDialog.show();
	}

	private void addXPic() {
		upClear();
		if (xpicDialog == null) {
			xpicDialog = MMAlert.createTwoChoicAlertNoTitle(this, R.string.common_camera, R.string.common_gallery, new MMAlert.DialogOnItemClickListener() {

				@Override
				public void onItemClickListener(View v, int position) {
					int id = v.getId();
					switch (id) {
					case R.id.item_first:
						if (!ImageTools.isSDCardExist()) {
							ToastMsg.showToastMsg(mContext, "sd卡不可用");
							return;
						}
						Intent cameraIntent = null;
						picFile = ImageTools.initTempFile();
						cameraIntent = ImageTools.getTakeCameraIntent(Uri.fromFile(picFile));
						startActivityForResult(cameraIntent, XACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA);
						xpicDialog.dismiss();
						break;

					case R.id.item_second:
						Intent photoIntent = null;
						photoIntent = new Intent(mContext, XPicSelectAct.class);
						mContext.startActivity(photoIntent);
						break;
					}
				}

			});
		}
		xpicDialog.show();
	}

	/**
	 * @说明:上传前的清空操作
	 * @author: zwy
	 */
	private void upClear() {
		tempUrls.clear();
		upUrls.clear();
		tupImgs.clear();
		upCount = 0;
		tags.clear();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case ACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA:
			if (Bimp.drr.size() < 10 && picFile != null || picFile.exists()) {
				String cameraImgPath = picFile.getAbsolutePath();
				// 重新把bitmap型变成File；
				picFile = ImageTools.saveImgForUpload(cameraImgPath);
				Bimp.drr.add(picFile.getPath());
				imgUrlArray.add(picFile.getPath());
			}
			break;
		case ZACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA:
			if (Bimpz.drrz.size() < 10 && picFile != null || picFile.exists()) {
				String cameraImgPath = picFile.getAbsolutePath();
				// 重新把bitmap型变成File；
				picFile = ImageTools.saveImgForUpload(cameraImgPath);
				Bimpz.drrz.add(picFile.getPath());
				imgZurls.add(picFile.getPath());
			}
			break;
		case XACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA:
			if (Bimpx.drrx.size() < 10 && picFile != null || picFile.exists()) {
				String cameraImgPath = picFile.getAbsolutePath();
				// 重新把bitmap型变成File；
				picFile = ImageTools.saveImgForUpload(cameraImgPath);
				Bimpx.drrx.add(picFile.getPath());
				imgXurls.add(picFile.getPath());
			}
			break;
		case TYPE_REQUEST_CODE:
			String type = data.getStringExtra("type");
			typeId = data.getStringExtra("typeId");
			etType.setText(type);
			break;
		case REQ_CODE_SELECT_AREA:
			int areaId = data.getIntExtra("CHOICE_AREA_RESULT_ID", -1);
			mAreaID = areaId == -1 ? "" : (areaId + "");
			// mShopTransferBean.shopAdress =
			// data.getStringExtra("CHOICE_AREA_RESULT");
			tvQu.setText(data.getStringExtra("CHOICE_AREA_RESULT").replace(" ", "").replace("中国", ""));
			break;
		}
	}

	private OnItemClickListener myClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			if (arg0.getChildCount() - 1 == arg2 && (arg0.getChildCount() != 5 || count == 4)) {
				addPic();
			} else {
				Intent intent = new Intent(MyProgramActivity.this, PhotoAct.class);
				intent.putExtra("ID", arg2);
				startActivity(intent);
			}
		}
	};

	@Override
	protected void onRestart() {
		super.onRestart();
		if (Bimp.drr != null) {
			Bimp.drr.remove("");
			count = Bimp.drr.size();
			if (Bimp.drr != null && Bimp.drr.size() > 0) {
				addPic_layout.setVisibility(View.GONE);
				displayUploadPic_gv.setVisibility(View.VISIBLE);
				if (Bimp.drr.size() < 5) {
					Bimp.drr.add("");
				}
				adapter.setGroup(Bimp.drr);
			} else {
				addPic_layout.setVisibility(View.VISIBLE);
				displayUploadPic_gv.setVisibility(View.GONE);
			}
		}
		if (Bimpz.drrz != null) {
			Bimpz.drrz.remove("");
			zCount = Bimpz.drrz.size();
			if (Bimpz.drrz != null && Bimpz.drrz.size() > 0) {
				addZPicLayout.setVisibility(View.GONE);
				showZPic.setVisibility(View.VISIBLE);
				if (Bimpz.drrz.size() < 5) {
					Bimpz.drrz.add("");
				}
				zAdapter.setGroup(Bimpz.drrz);
			} else {
				addZPicLayout.setVisibility(View.VISIBLE);
				showZPic.setVisibility(View.GONE);
			}
		}
		if (Bimpx.drrx != null) {
			Bimpx.drrx.remove("");
			xCount = Bimpx.drrx.size();
			if (Bimpx.drrx != null && Bimpx.drrx.size() > 0) {
				addXPicLayout.setVisibility(View.GONE);
				showXPic.setVisibility(View.VISIBLE);
				if (Bimpx.drrx.size() < 5) {
					Bimpx.drrx.add("");
				}
				xAdapter.setGroup(Bimpx.drrx);
			} else {
				addXPicLayout.setVisibility(View.VISIBLE);
				showXPic.setVisibility(View.GONE);
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		imgUrlArray.clear();
		Bimp.drr.clear();
		tDImgUrls.clear();
		imgZurls.clear();
		Bimpz.drrz.clear();
		tZImgUrls.clear();
		imgXurls.clear();
		Bimpx.drrx.clear();
		tXImgUrls.clear();
	}

	@Override
	protected void onResume() {
		// if (imgUrlArray != null && Bimp.drr != null) {
		//
		// DebugTool.i("zwy", "" + imgUrlArray.size());
		// StringBuilder str = new StringBuilder();
		// for (int i = 0; i < imgUrlArray.size(); i++) {
		// str.append(imgUrlArray.get(i) + ",");
		// }
		// DebugTool.i("zwy", str.toString());
		// DebugTool.i("zwy", "" + Bimp.drr.size());
		// StringBuilder str2 = new StringBuilder();
		// for (int i = 0; i < Bimp.drr.size(); i++) {
		// str2.append(Bimp.drr.get(i) + ",");
		// }
		// DebugTool.i("zwy", str2.toString());
		// }
		super.onResume();
	}

	private void initNet() {
		showLoadingDialog("");
		FormResultRequest<MyProgramBean> request = new FormResultRequest<MyProgramBean>(UrlConstants.URL_PROJECT_DETAIL, initListener, this,
				new TypeToken<RequestResult<MyProgramBean>>() {
				}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putStringTypeParam("userId", userModel.getUserId());
		ajaxParams.putStringTypeParam("projectId", userModel.getProjectId());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	private void uploadImgNet(String path) {
		try {
			// File picFile = new File(path);
			File picFile = ImageTools.saveImgForUpload(path);
			FormResultRequest<UpImageBean> request = new FormResultRequest<UpImageBean>(UrlConstants.UPLOADIMG, uploadListener, upErrorListener,
					new TypeToken<RequestResult<UpImageBean>>() {
					}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();//
			ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());// userId
			if (picFile != null) {
				ajaxParams.putStringTypeParam("validateKey", FileTool.getMD5FromFile(picFile));
				ajaxParams.put(new FileTypeParam("fileName", picFile.getPath(), FileUtils.getMimeType(Uri.fromFile(new File(picFile.getPath())).toString())));
			}
			request.setRequestParams(ajaxParams);
			executeRequest(request, path);
			tags.add(path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void release() {
		if (isUp) {
			showToastMsg("正在发布中，请稍候");
			return;
		}
		String merchantName = getInputStr(etMerName);
		if (TextUtils.isEmpty(merchantName)) {
			showToastMsg("请输入商家姓名");
			return;
		}
		String shopName = getInputStr(etShopName);
		if (TextUtils.isEmpty(shopName)) {
			showToastMsg("请输入店铺名称");
			return;
		}
		String mobile = getInputStr(etPhone);
		if (TextUtils.isEmpty(mobile)) {
			showToastMsg("请输入联系电话");
			return;
		}
		String regex = "^(13[0-9]|14[57]|15[0-9]|17[012356789]|18[0-9])\\d{8}$";
		boolean result = Pattern.compile(regex).matcher(mobile).find();
		if (!result) {
			Toast.makeText(context, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
			return;
		}
		String shopAddress = getInputStr(etAddress);
		if (TextUtils.isEmpty(shopAddress)) {
			showToastMsg("请输入店铺地址");
			return;
		}
		if (upDImgs.size() == 0) {
			showToastMsg("请上传店面照片");
			return;
		}
		if (upZImgs.size() == 0) {
			showToastMsg("请上传装修照片");
			return;
		}
		String projectName = getInputStr(etProName);
		if (TextUtils.isEmpty(projectName)) {
			showToastMsg("请输入项目名称");
			return;
		}
		if (TextUtils.isEmpty(typeId)) {
			showToastMsg("请选择分类");
			return;
		}
		String courseLength = getInputStr(etTime);
		if (TextUtils.isEmpty(courseLength)) {
			showToastMsg("请输入学习时间");
			return;
		}
		String description = getInputStr(etIntroduce);
		if (TextUtils.isEmpty(description)) {
			showToastMsg("请输入项目介绍");
			return;
		}
		if (upXImgs.size() == 0) {
			showToastMsg("请上传项目照片");
			return;
		}
		showLoadingDialog("发布中");
		/**
		 * 如果存在删除的图片，则先删除后提交发布
		 */
		if (delImgBeans.size() > 0 && GlobalApp.userModel.getProjectId() != null && !TextUtils.isEmpty(GlobalApp.userModel.getProjectId())) {
			for (int i = 0; i < delImgBeans.size(); i++) {
				DelImgBean bean = delImgBeans.get(i);
				delNet(bean.getImageId(), String.valueOf(bean.getType()));
			}
		} else {// 如果没有删除操作，则直接提交发布
			releaseNet();
		}
	}

	public void releaseNet() {
		isUp = true;
		FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.UPDATEORADDPROJECT, releaseListener, releaseError, new TypeToken<RequestResult<String>>() {
		}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putStringTypeParam("userId", userModel.getUserId());
		ajaxParams.putStringTypeParam("shopAddress", getInputStr(etAddress));
		ajaxParams.putStringTypeParam("shopName", getInputStr(etShopName));
		ajaxParams.putStringTypeParam("mobile", getInputStr(etPhone));
		ajaxParams.putStringTypeParam("merchantId", TextUtils.isEmpty(userModel.getProjectId()) ? "0" : userModel.getUserId());
		ajaxParams.putStringTypeParam("projectId", TextUtils.isEmpty(userModel.getProjectId()) ? "0" : userModel.getProjectId());
		ajaxParams.putStringTypeParam("merchantName", getInputStr(etMerName));
		ajaxParams.putStringTypeParam("latitude", locationBean == null || locationBean.latitude == 0.0 ? "0" : String.valueOf(locationBean.latitude));
		ajaxParams.putStringTypeParam("longitude", locationBean == null || locationBean.longtitude == 0.0 ? "0" : String.valueOf(locationBean.latitude));
		ajaxParams.putStringTypeParam("typeId", typeId);
		ajaxParams.putStringTypeParam("price", getInputStr(etPrice));
		ajaxParams.putStringTypeParam("courseLength", getInputStr(etTime));
		ajaxParams.putStringTypeParam("projectName", getInputStr(etProName));
		ajaxParams.putStringTypeParam("areaId", mAreaID);
		ajaxParams.putStringTypeParam("description", getInputStr(etIntroduce));
		if (upDImgs.size() > 0 || upZImgs.size() > 0 || upXImgs.size() > 0) {
			ajaxParams.putCommonTypeParam("modifyImageArray", getModifyImage());
		}
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	// @Override
	// public String getInputStr(EditText et) {
	// String str = super.getInputStr(et);
	// return TextUtils.isEmpty(str) ? " " : str;
	// }

	public String getModifyImage() {
		ArrayList<UpImgIdBean> list = new ArrayList<UpImgIdBean>();
		Set<Map.Entry<String, String>> denSet = upDImgs.entrySet();
		Iterator<Map.Entry<String, String>> dit = denSet.iterator();
		while (dit.hasNext()) {
			Map.Entry<String, String> entry = dit.next();
			UpImgIdBean bean = new UpImgIdBean(entry.getValue(), "1");
			list.add(bean);
		}
		Set<Map.Entry<String, String>> zenSet = upZImgs.entrySet();
		Iterator<Map.Entry<String, String>> zit = zenSet.iterator();
		while (zit.hasNext()) {
			Map.Entry<String, String> entry = zit.next();
			UpImgIdBean bean = new UpImgIdBean(entry.getValue(), "2");
			list.add(bean);
		}
		Set<Map.Entry<String, String>> xenSet = upXImgs.entrySet();
		Iterator<Map.Entry<String, String>> xit = xenSet.iterator();
		while (xit.hasNext()) {
			Map.Entry<String, String> entry = xit.next();
			UpImgIdBean bean = new UpImgIdBean(entry.getValue(), "3");
			list.add(bean);
		}

		Gson gson = new Gson();
		return gson.toJson(list);
	}

	private Listener<RequestResult<MyProgramBean>> initListener = new Listener<RequestResult<MyProgramBean>>() {
		@Override
		public void onResponse(RequestResult<MyProgramBean> arg0) {
			dismissLoadingDialog();
			if (arg0.flag == 1 && arg0.getRs() != null) {
				MyProgramBean bean = arg0.getRs();
				etMerName.setText("null".equals(bean.getUserName()) ? "" : bean.getUserName());
				etShopName.setText("null".equals(bean.getShopName()) ? "" : bean.getShopName());
				tvQu.setText(bean.getAreaName() == null || "null".equals(bean.getAreaName()) || TextUtils.isEmpty(bean.getAreaName()) ? "宝安区" : bean.getAreaName());
				etAddress.setText("null".equals(bean.getAddress()) ? "" : bean.getAddress());
				etProName.setText("null".equals(bean.getProjectName()) ? "" : bean.getProjectName());
				etPhone.setText("null".equals(bean.getPhone()) ? "" : bean.getPhone());
				etType.setText("null".equals(bean.getTypeName()) ? "" : bean.getTypeName());
				typeId = bean.getCategoryID();
				etPrice.setText("null".equals(bean.getTradePrice()) ? "" : bean.getTradePrice());
				etTime.setText("null".equals(bean.getLearningTime()) ? "" : bean.getLearningTime());
				etIntroduce.setText("null".equals(bean.getIntroduction()) ? "" : bean.getIntroduction());
				if (!"null".equals(bean.getUserName()) && !TextUtils.isEmpty(bean.getUserName())&& !"null".equals(bean.getAuditStatus())) {
					String status = "";
					switch (Integer.parseInt(bean.getAuditStatus())) {// 审核状态(1-待审核 2-审核 3-拒接)
					case 1:
						status = "您提交的商家信息正在审核中，我们会在2天内完成审核，请耐心等待";
						break;
					case 2:
						status = "您提交的商家信息审核通过";
						break;
					case 3:
						status = String.format("您提交的商家信息审核拒绝，原因：%s", bean.getAuditRemark());
						break;
					default:
						break;
					}
					tvStatus.setVisibility(View.VISIBLE);
					tvStatus.setText(status);
				}else{
					tvStatus.setVisibility(View.GONE);
				}
				setImage(bean.getImageArray());
			}
		}
	};
	private Listener<RequestResult<UpImageBean>> uploadListener = new Listener<RequestResult<UpImageBean>>() {
		@Override
		public void onResponse(RequestResult<UpImageBean> arg0) {
			// showToastMsg(arg0.msg);
			// tempUrls.add(rs.get("imageId"));
			UpImageBean bean = arg0.getRs();
			if (bean != null) {
				tupImgs.put(FileTool.getFileName(bean.getFileName()), bean.getImageId());
			}
			if (tupImgs.size() == upCount) {
				dismissLoadingDialog();
				isUpSuccess = true;
				switch (upType) {
				case 1:
					upDImgs.putAll(tupImgs);
					break;
				case 2:
					upZImgs.putAll(tupImgs);
					break;
				case 3:
					upXImgs.putAll(tupImgs);
					break;

				default:
					break;
				}
			}
		}
	};

	private Listener<RequestResult<String>> releaseListener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			dismissLoadingDialog();
			if (arg0.flag == 1) {
				GlobalApp.userModel.setProjectId(arg0.getRs());
				GlobalApp.userModel.setHasProject(1);
				Intent intent = new Intent(MyProgramActivity.this, SubmitSuccessActivity.class);
				intent.putExtra("succesTip", "提交创业项目成功");
				intent.putExtra("succesPrompt", arg0.msg);
				showActivity(aty, intent);
				aty.finish();
			} else {
				showToastMsg(arg0.msg);
			}
		}
	};

	private void delNet(String imgId, String imgType) {
		FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.DELETIMAGE, delistener, new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError arg0) {// 调删除接口失败后,把删除的图片重新显示
				dismissLoadingDialog();
				showToastMsg("图片删除失败!");
				for (int i = 0; i < delImgBeans.size(); i++) {
					DelImgBean bean = delImgBeans.get(i);
					switch (bean.getType()) {
					case 1:
						imgUrlArray.add(bean.getFilePath());
						Bimp.drr.add(bean.getFilePath());
						break;
					case 2:
						imgZurls.add(bean.getFilePath());
						Bimpz.drrz.add(bean.getFilePath());
						break;
					case 3:
						imgXurls.add(bean.getFilePath());
						Bimpx.drrx.add(bean.getFilePath());
						break;
					default:
						break;
					}
				}
				onRestart();
			}
		}, new TypeToken<RequestResult<String>>() {
		}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putStringTypeParam("type", imgType);
		ajaxParams.putStringTypeParam("imageId", imgId);
		if ("1".equals(imgType) || "2".equals(imgType)) {// 店面照片、装修照片
			ajaxParams.putStringTypeParam("merchantId", userModel.getUserId());
		} else {// 项目照片
			ajaxParams.putStringTypeParam("projectId", userModel.getProjectId());
		}
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	private Listener<RequestResult<String>> delistener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			delUpCount++;
			if (delUpCount == delImgBeans.size()) {
				handler.sendEmptyMessageDelayed(1, 1000);
			}
		}
	};

	public void onEventMainThread(ImgActionEvent actionEvent) {
		upType = actionEvent.getType();
		if (actionEvent.getAction() == 1) {// 增加
			// uploadImgNet(actionEvent.getPath());
			upUrls.add(actionEvent.getPath());
			// mHandler.sendEmptyMessageDelayed(0, 500);
		} else {
			upUrls.remove(actionEvent.getPath());
		}
	}

	public void onEventMainThread(ImgUpEvent upEvent) {
		upCount = upUrls.size();
		if (upCount == 0) {
			return;
		}

		switch (upType) {
		case 1:
			tDImgUrls.addAll(upUrls);
			break;
		case 2:
			tZImgUrls.addAll(upUrls);
			break;
		case 3:
			tXImgUrls.addAll(upUrls);
			break;

		default:
			break;
		}
		// uploadImgNet(upUrls.get(upIndex));
		loadingDialog("上传照片");
		handler.sendEmptyMessageDelayed(0, 1000);
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				for (int i = 0; i < upCount; i++) {
					final int j = i;
//					new Thread(new Runnable() {
//						@Override
//						public void run() {
//							uploadImgNet(upUrls.get(j));
//						}
//					}).start();
					upImgThreadPool.execute(new Runnable() {
						@Override
						public void run() {
							uploadImgNet(upUrls.get(j));
						}
					});
				}
				handler.sendEmptyMessageDelayed(2, 60 * 1000);
				break;
			case 1:
				releaseNet();
				break;
			case 2:
				if (!isUpSuccess) {
					upErrorListener.onErrorResponse(new VolleyError());
					for (int i = 0; i < tags.size(); i++) {
						cancelRequest(tags.get(i));
					}
				}
				break;
			default:
				break;
			}

		};
	};

	public void onEventMainThread(ImgDelEvent delEvent) {
		switch (delEvent.getType()) {
		case 1:
			delImgs.put(upDImgs.get(FileTool.getFileName(tDImgUrls.get(delEvent.getIndex()))), "1");
			delImgBeans.add(new DelImgBean(tDImgUrls.get(delEvent.getIndex()), upDImgs.get(FileTool.getFileName(tDImgUrls.get(delEvent.getIndex()))), 1));
			upDImgs.remove(FileTool.getFileName(tDImgUrls.get(delEvent.getIndex())));
			tDImgUrls.remove(delEvent.getIndex());
			break;
		case 2:
			delImgs.put(upZImgs.get(FileTool.getFileName(tZImgUrls.get(delEvent.getIndex()))), "2");
			delImgBeans.add(new DelImgBean(tZImgUrls.get(delEvent.getIndex()), upZImgs.get(FileTool.getFileName(tZImgUrls.get(delEvent.getIndex()))), 2));
			upZImgs.remove(FileTool.getFileName(tZImgUrls.get(delEvent.getIndex())));
			tZImgUrls.remove(delEvent.getIndex());
			break;
		case 3:
			delImgs.put(upXImgs.get(FileTool.getFileName(tXImgUrls.get(delEvent.getIndex()))), "3");
			delImgBeans.add(new DelImgBean(tXImgUrls.get(delEvent.getIndex()), upXImgs.get(FileTool.getFileName(tXImgUrls.get(delEvent.getIndex()))), 3));
			upXImgs.remove(FileTool.getFileName(tXImgUrls.get(delEvent.getIndex())));
			tXImgUrls.remove(delEvent.getIndex());
			break;

		default:
			break;
		}
	}

	/**
	 * @说明:初始化页面时，加载图片 先从缓存文件中使用该url来找，如果不存在图片，再从网上下载
	 *                 把下载的图片保存到图片，再设置到相对应的集合中显示出来
	 * @author: zwy
	 */
	public void setImage(ArrayList<MyProgramImg> imgs) {
		if (imgs != null && imgs.size() > 0) {
			for (int i = 0; i < imgs.size(); i++) {
				final String url = imgs.get(i).getImageUrl();
				final int type = imgs.get(i).getType();
				String imgId = imgs.get(i).getImageID();
				switch (type) {
				case 1:
					upDImgs.put(FileTool.getFileName(url), imgId);
					break;
				case 2:
					upZImgs.put(FileTool.getFileName(url), imgId);
					break;
				case 3:
					upXImgs.put(FileTool.getFileName(url), imgId);
					break;
				default:
					break;
				}
				String filePath = FileTool.getFilePath(url);
				if (!TextUtils.isEmpty(filePath)) {
					switch (type) {
					case 1:
						imgUrlArray.add(filePath);
						Bimp.drr.add(filePath);
						tDImgUrls.add(filePath);
						break;
					case 2:
						imgZurls.add(filePath);
						Bimpz.drrz.add(filePath);
						tZImgUrls.add(filePath);
						break;
					case 3:
						imgXurls.add(filePath);
						Bimpx.drrx.add(filePath);
						tXImgUrls.add(filePath);
						break;

					default:
						break;
					}
					onRestart();
				} else {
					loadImage(url, type);
				}
			}
		}

	}

	/**
	 * @说明:从网络下载图片
	 * @author: zwy
	 */
	public void loadImage(String url, final int type) {
		imageLoader.loadImage(url, options, new ImageLoadingListener() {
			@Override
			public void onLoadingStarted(String arg0, View arg1) {

			}

			@Override
			public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
				// switch (type) {
				// case 1:
				// imgUrlArray.add(defultImg);
				// Bimp.drr.add(defultImg);
				// tDImgUrls.add(defultImg);
				// break;
				// case 2:
				// imgZurls.add(defultImg);
				// Bimpz.drrz.add(defultImg);
				// tZImgUrls.add(defultImg);
				// break;
				// case 3:
				// imgXurls.add(defultImg);
				// Bimpx.drrx.add(defultImg);
				// tXImgUrls.add(defultImg);
				// break;
				// default:
				// break;
				// }

			}

			@Override
			public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
				try {
					FileTool.saveFile(arg2, FileTool.getFileName(arg0), "");
					switch (type) {
					case 1:
						imgUrlArray.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						Bimp.drr.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						tDImgUrls.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						break;
					case 2:
						imgZurls.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						Bimpz.drrz.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						tZImgUrls.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						break;
					case 3:
						imgXurls.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						Bimpx.drrx.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						tXImgUrls.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						break;

					default:
						break;
					}

					// File file = imageLoader.getDiskCache().get(url);
					onRestart();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onLoadingCancelled(String arg0, View arg1) {

			}
		});
	}

	private ErrorListener upErrorListener = new ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError arg0) {
			dismissLoadingDialog();
			showToastMsg("图片上传失败");
			switch (upType) {
			case 1:
				imgUrlArray.removeAll(upUrls);
				Bimp.drr.clear();
				Bimp.drr.addAll(imgUrlArray);
				tDImgUrls.removeAll(upUrls);
				break;
			case 2:
				imgZurls.removeAll(upUrls);
				Bimpz.drrz.clear();
				Bimpz.drrz.addAll(imgZurls);
				tZImgUrls.removeAll(upUrls);
				break;
			case 3:
				imgXurls.removeAll(upUrls);
				Bimpx.drrx.clear();
				Bimpx.drrx.addAll(imgXurls);
				tXImgUrls.removeAll(upUrls);
				break;

			default:
				break;
			}
			onRestart();
		}
	};

	/**
	 * 检查定位，查找区域id并展示结果
	 * 
	 * @param showError
	 * @return
	 * @author FAN 创建于Mar 19, 2015
	 */
	AreaInfoDbHelper areaInfoDbHelper;

	private boolean checkLocationError(boolean showError) {
		locationCount++;
		if (locationBean == null || TextUtils.isEmpty(locationBean.province)) {
			if (showError && locationCount > 1) {
				showToastMsg("定位失败");
			}
			return true;
		} else {
			tvQu.setText(locationBean.toShortAddress());
			etAddress.setText(locationBean.getDetailAddress());
			// 查找区域id areaId
			if (areaInfoDbHelper == null) {
				areaInfoDbHelper = new AreaInfoDbHelper();
			}
			String namePath = locationBean.province + "^" + locationBean.city + "^" + locationBean.district;
			mAreaID = "" + areaInfoDbHelper.getAreaIDByNamePath(namePath);
			locationSuccess = true;
			return false;
		}
	}

	@Override
	public void onLocation(LocationBean locationBean) {
		this.locationBean = locationBean;
		checkLocationError(true);
		gaodeMapHelper.stop();
	}

	private TextWatcher phoneWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (s.length() > 0) {
				if (!s.toString().substring(0, 1).equals("1")) {// 电话号码第一个只能为1
					etPhone.setText("");
				} else if (s.length() > 1 && !s.toString().substring(1, 2).matches("[3-8]")) {// 电话号码第二个为3-8
					etPhone.setText("1");
					etPhone.setSelection(etPhone.length());
				}
			}

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	private ErrorListener releaseError = new ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			dismissLoadingDialog();
			isUp = false;
			if (CURRENT_PAGE > 1) {// 加载异常回退到当前页
				CURRENT_PAGE--;
			}
			String msg = "网络异常";
			if (error instanceof ServerFlagError) {
				msg = ((ServerFlagError) error).result.msg;
			} else if (error instanceof ServerJsonUnParseError) {
				try {
					String res = ((ServerJsonUnParseError) error).result;
					JSONObject jsonObject = new JSONObject(res);
					msg = jsonObject.getString("msg");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				try {
					if (error.networkResponse != null && error.networkResponse.data != null) {
						msg = new String(error.networkResponse.data, "utf-8");
						if (TextUtils.isEmpty(msg)) {
							msg = "未知异常";
						}
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			showToastMsg(msg);
		}
	};

	public void loadingDialog(String parameter) {
		initLoadingDialog(true);// 透明
		loadingDialog.setTitle(parameter);
		loadingDialog.setCancelable(false);
		loadingDialog.setCanceledOnTouchOutside(false);
		if (!loadingDialog.isShowing())
			loadingDialog.show();
	}

	@Override
	public void onBackPressed() {
		dialog = MMAlert.createShowCenterDialog(this, "温馨提示", "确定要退出？", "取消", "确定", new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		}, new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		dialog.show();
		// super.onBackPressed();
	}

}
